package cn.stronglink.assetmanage.business.task.model;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.media.MediaCas;
import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import junit.framework.Assert;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.dao.AssetDao;
import cn.stronglink.assetmanage.dao.CheckDao;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.DaoSession;
import cn.stronglink.assetmanage.dao.InventoryDao;
import cn.stronglink.assetmanage.dao.InventoryDetailDao;
import cn.stronglink.assetmanage.dao.PatrolDao;
import cn.stronglink.assetmanage.dao.PatrolDetailDao;
import cn.stronglink.assetmanage.dao.RepailDetailDao;
import cn.stronglink.assetmanage.dao.RepairDao;
import cn.stronglink.assetmanage.dao.TaskDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.Inventory;
import cn.stronglink.assetmanage.entity.InventoryDetail;
import cn.stronglink.assetmanage.entity.Patrol;
import cn.stronglink.assetmanage.entity.PatrolDetail;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Task;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.netrequest.business.check.CheckService;
import cn.stronglink.netrequest.business.inventory.InventoryService;
import cn.stronglink.netrequest.business.repail.RepairService;
import cn.stronglink.netrequest.exceptions.BusinessErrorException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by chencongcong on 2018/6/18.
 */

public class TaskSyncModel {
    private Gson gson;
    private CheckService checkService;
    private InventoryService inventoryService;
    private RepairService repairService;
    private ITaskSyncListener listener;
    private DaoSession session;
    private Handler mHandler = new Handler();

    public TaskSyncModel() {
        gson = new Gson();
        checkService = new CheckService();
        inventoryService = new InventoryService();
        repairService = new RepairService();
        session = DaoManager.getDaoSession(MyApplication.APP_CONTEXT);
    }

    public ITaskSyncListener getListener() {
        return listener;
    }

    public void setListener(ITaskSyncListener listener) {
        this.listener = listener;
    }

    public List<Task> getSyncList() {
        List<Task> taskList = new ArrayList<>();
        DaoSession session = DaoManager.getDaoSession(MyApplication.APP_CONTEXT);
        List<Check> checkList = session.getCheckDao().queryBuilder().where(CheckDao.Properties.Status.eq(4)).list();
        List<Inventory> inventorieList = session.getInventoryDao().queryBuilder().where(InventoryDao.Properties.Status.eq(3)).list();
        List<Repair> repairList = session.getRepairDao().queryBuilder().where(RepairDao.Properties.Status.eq(3)).list();
        List<Patrol> patrolList = session.getPatrolDao().queryBuilder().where(PatrolDao.Properties.Status.eq(3)).list();
        if (checkList != null && checkList.size() > 0) {
            for (Check check : checkList) {
                Task task = new Task();
                task.setId_(check.getId_());
                task.setStatus(check.getStatus());
                task.setBusinessType(1);
                task.setStatusName("已入库");
                taskList.add(task);
            }
        }

        if (inventorieList != null && inventorieList.size() > 0) {
            for (Inventory inventory : inventorieList) {
                Task task = new Task();
                task.setId_(inventory.getId_());
                task.setStatus(inventory.getStatus());
                task.setBusinessType(2);
                task.setStatusName("已盘点");
                taskList.add(task);
            }
        }

        if (repairList != null && repairList.size() > 0) {
            for (Repair repair : repairList) {
                Task task = new Task();
                task.setId_(repair.getId_());
                task.setStatus(repair.getStatus());
                task.setBusinessType(3);
                task.setStatusName("已维修");
                taskList.add(task);
            }
        }

        if (patrolList != null && patrolList.size() > 0) {
            for (Patrol patrol : patrolList) {
                Task task = new Task();
                task.setId_(patrol.getId_());
                task.setStatus(patrol.getStatus());
                task.setBusinessType(4);
                task.setStatusName("已巡检");
                taskList.add(task);
            }
        }
        return taskList;
    }

    int sum;

    public void sync() {
        sum = 0;
        try {
            List<Check> checkList = session.getCheckDao().queryBuilder().where(CheckDao.Properties.Status.eq(4)).list();
            List<Inventory> inventorieList = session.getInventoryDao().queryBuilder().where(InventoryDao.Properties.Status.eq(3)).list();
            List<Repair> repairList = session.getRepairDao().queryBuilder().where(RepairDao.Properties.Status.eq(3)).list();
            List<Patrol> patrolList = session.getPatrolDao().queryBuilder().where(PatrolDao.Properties.Status.eq(3)).list();
            sum = checkList.size() + inventorieList.size() + repairList.size() + patrolList.size();
            uploadCheckList(checkList);
            uploadInventoryList(inventorieList);
            uploadRepairList(repairList);
            uploadPatrolList(patrolList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadPatrolList(List<Patrol> patrolList) {
        if (patrolList != null && patrolList.size() > 0) {
            for (Patrol patrol : patrolList) {
                patrol.setId(Long.valueOf(patrol.getId_()));
                List<PatrolDetail> patrolDetailList = session.getPatrolDetailDao().queryBuilder()
                        .where(PatrolDetailDao.Properties.OrderNo.eq(patrol.getId_())).list();
                if (patrolDetailList != null && patrolDetailList.size() > 0) {
                    for (PatrolDetail detail : patrolDetailList) {
                        if (detail.getId_() != null && !detail.getId_().isEmpty()) {
                            detail.setId(Long.valueOf(detail.getId_()));
                        }
                        if (detail.getBrandId_() != null && !detail.getBrandId_().isEmpty()) {
                            detail.setBrandId(Long.valueOf(detail.getBrandId_()));
                        }
                        if (detail.getModelId_() != null && !detail.getModelId_().isEmpty()) {
                            detail.setModelId(Long.valueOf(detail.getModelId_()));
                        }
                        if (detail.getTypeId_() != null && !detail.getTypeId_().isEmpty()) {
                            detail.setTypeId(Long.valueOf(detail.getTypeId_()));
                        }
                        if (detail.getDatacenterId_() != null && !detail.getDatacenterId_().isEmpty()) {
                            detail.setDatacenterId(Long.valueOf(detail.getDatacenterId_()));
                        }
                        if (detail.getManageBranchId_() != null && !detail.getManageBranchId_().isEmpty()) {
                            detail.setManageBranchId(Long.valueOf(detail.getManageBranchId_()));
                        }
                        if (detail.getRoomId_() != null && !detail.getRoomId_().isEmpty()) {
                            detail.setRoomId(Long.valueOf(detail.getRoomId_()));
                        }
                        if (detail.getUseBranchId_() != null && !detail.getUseBranchId_().isEmpty()) {
                            detail.setUseBranchId(Long.valueOf(detail.getUseBranchId_()));
                        }
                    }
                    patrol.setDetailList(patrolDetailList);
                }

                uploadPatrol(patrol);
            }
        }
    }

    public void uploadPatrol(final Patrol patrol) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = gson.toJson(patrol);
                try {
                    repairService.uploadRepairWorkOrder(json, new Callback() {
                        @Override
                        public void onFailure(Call call, final IOException e) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (listener != null) {
                                        listener.onFail(patrol.getId_(), OrderType.PATROL, e, --sum);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String json = response.body().string();
                            if (json != null) {
                                final Result<String> result = gson.fromJson(json, new TypeToken<Result<String>>() {
                                }.getType());
                                if (result != null && result.getHttpCode() == 200) {
                                    // 删除本地单子
                                    session.getPatrolDao().deleteByKey(patrol.getPatrol_id());
                                    session.getPatrolDetailDao().deleteInTx(patrol.getDetailList());
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onSucces(patrol.getId_(), OrderType.PATROL, --sum);
                                            }
                                        }
                                    });

                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onFail(patrol.getId_(), OrderType.PATROL, new BusinessErrorException(result.getMsg()), --sum);
                                            }
                                        }
                                    });

                                }
                            }
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null) {
                                listener.onFail(patrol.getId_(), OrderType.PATROL, e, --sum);
                            }
                        }
                    });

                }
            }
        }).start();
    }

    public void uploadRepairList(List<Repair> repairList) {
        if (repairList != null && repairList.size() > 0) {
            for (Repair repair : repairList) {
                if (repair.getId_() != null && !repair.getId_().isEmpty()) {
                    repair.setId(Long.valueOf(repair.getId_()));
                }
                List<RepailDetail> repailDetailList = session.getRepailDetailDao().queryBuilder()
                        .where(RepailDetailDao.Properties.RepairId_.eq(repair.getId_())).list();
                if (repailDetailList != null && repailDetailList.size() > 0) {
                    for (RepailDetail detail : repailDetailList) {
                        if (detail.getId_() != null && !detail.getId_().isEmpty()) {
                            detail.setId(Long.valueOf(detail.getId_()));
                        }
                        if (detail.getRepairId_() != null && !detail.getRepairId_().isEmpty()) {
                            detail.setRepairId(Long.valueOf(detail.getRepairId_()));
                        }
                    }
                    repair.setDetailList(repailDetailList);
                }

                uploadRepair(repair);
            }
        }
    }

    public void uploadRepair(final Repair repair) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = gson.toJson(repair);
                try {
                    repairService.uploadRepairWorkOrder(json, new Callback() {
                        @Override
                        public void onFailure(Call call, final IOException e) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (listener != null) {
                                        listener.onFail(repair.getId_(), OrderType.REPAIR, e, --sum);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String json = response.body().string();
                            if (json != null) {
                                final Result<String> result = gson.fromJson(json, new TypeToken<Result<String>>() {
                                }.getType());
                                if (result != null && result.getHttpCode() == 200) {
                                    // 删除本地单子
                                    session.getRepairDao().deleteByKey(repair.getRepair_id());
                                    session.getRepailDetailDao().deleteInTx(repair.getDetailList());
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onSucces(repair.getId_(), OrderType.REPAIR, --sum);
                                            }
                                        }
                                    });
                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onFail(repair.getId_(), OrderType.REPAIR, new BusinessErrorException(result.getMsg()), --sum);
                                            }
                                        }
                                    });

                                }
                            }
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null) {
                                listener.onFail(repair.getId_(), OrderType.REPAIR, e, --sum);
                            }
                        }
                    });

                }
            }
        }).start();
    }

    public void uploadInventoryList(List<Inventory> inventorieList) {
        if (inventorieList != null && inventorieList.size() > 0) {
            for (Inventory inventory : inventorieList) {
                if (inventory.getId_() != null && !inventory.getId_().isEmpty()) {
                    inventory.setId(Long.valueOf(inventory.getId_()));
                }
                // 正常盘点列表
                List<InventoryDetail> inventoryDetailList = session.getInventoryDetailDao().queryBuilder()
                        .where(InventoryDetailDao.Properties.OrderNo.eq(inventory.getId_()), InventoryDetailDao.Properties.Status.eq(3)).list();
                if (inventoryDetailList != null && inventoryDetailList.size() > 0) {
                    for (InventoryDetail detail : inventoryDetailList) {
                        if (detail.getId_() != null && !detail.getId_().isEmpty()) {
                            detail.setId(Long.valueOf(detail.getId_()));
                        }
                        if (detail.getBrandId_() != null && !detail.getBrandId_().isEmpty()) {
                            detail.setBrandId(Long.valueOf(detail.getBrandId_()));
                        }
                        if (detail.getModelId_() != null && !detail.getModelId_().isEmpty()) {
                            detail.setModelId(Long.valueOf(detail.getModelId_()));
                        }
                        if (detail.getTypeId_() != null && !detail.getTypeId_().isEmpty()) {
                            detail.setTypeId(Long.valueOf(detail.getTypeId_()));
                        }
                        if (detail.getDatacenterId_() != null && !detail.getDatacenterId_().isEmpty()) {
                            detail.setDatacenterId(Long.valueOf(detail.getDatacenterId_()));
                        }
                        if (detail.getRoomId_() != null && !detail.getRoomId_().isEmpty()) {
                            detail.setRoomId(Long.valueOf(detail.getRoomId_()));
                        }
                    }
                    inventory.setDetailList(inventoryDetailList);
                }
                // 盘盈列表
                List<InventoryDetail> moreOutList = session.getInventoryDetailDao().queryBuilder()
                        .where(InventoryDetailDao.Properties.OrderNo.eq(inventory.getId_()), InventoryDetailDao.Properties.Status.eq(5)).list();
                if (moreOutList != null && moreOutList.size() > 0) {
                    inventory.setMoreOutList(moreOutList);
                }
                uploadInventory(inventory);
            }
        }
    }

    // 上传盘点单
    public void uploadInventory(final Inventory inventory) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = gson.toJson(inventory);
                try {
                    inventoryService.uploadInventoryList(json, new Callback() {
                        @Override
                        public void onFailure(Call call, final IOException e) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (listener != null) {
                                        listener.onFail(inventory.getId_(), OrderType.INVENTROY, e, --sum);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String json = response.body().string();
                            if (json != null) {
                                final Result<String> result = gson.fromJson(json, new TypeToken<Result<String>>() {
                                }.getType());
                                if (result != null && result.getHttpCode() == 200) {
                                    // 删除本地单子
                                    session.getInventoryDao().deleteByKey(inventory.getInventory_id());
                                    session.getInventoryDetailDao().deleteInTx(inventory.getDetailList());
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onSucces(inventory.getId_(), OrderType.INVENTROY, --sum);
                                            }
                                        }
                                    });

                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onFail(inventory.getId_(), OrderType.INVENTROY, new BusinessErrorException(result.getMsg()), --sum);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null) {
                                listener.onFail(inventory.getId_(), OrderType.INVENTROY, e, --sum);
                            }
                        }
                    });

                }
            }
        }).start();
    }


    public void uploadCheckList(List<Check> checkList) throws Exception {
        if (checkList != null && checkList.size() > 0) {
            for (Check check : checkList) {
                if (check.getId_() != null && !check.getId_().isEmpty()) {
                    check.setId(Long.valueOf(check.getId_()));
                }
                List<Asset> assetList = session.getAssetDao().queryBuilder().where(AssetDao.Properties.OrderNo.eq(check.getId_())).list();
                if (assetList != null && assetList.size() > 0) {
                    for (Asset asset : assetList) {
                        if (asset.getId_() != null && !asset.getId_().isEmpty()) {
                            asset.setId(Long.valueOf(asset.getId_()));
                        }
                        if (asset.getBrandId_() != null && !asset.getBrandId_().isEmpty()) {
                            asset.setBrandId(Long.valueOf(asset.getBrandId_()));
                        }
                        if (asset.getModelId_() != null && !asset.getModelId_().isEmpty()) {
                            asset.setModelId(Long.valueOf(asset.getModelId_()));
                        }
                        if (asset.getTypeId_() != null && !asset.getTypeId_().isEmpty()) {
                            asset.setTypeId(Long.valueOf(asset.getTypeId_()));
                        }
                        if (asset.getDatacenterId_() != null && !asset.getDatacenterId_().isEmpty()) {
                            asset.setDatacenterId(Long.valueOf(asset.getDatacenterId_()));
                        }
                        if (asset.getRoomId_() != null && !asset.getRoomId_().isEmpty()) {
                            asset.setRoomId(Long.valueOf(asset.getRoomId_()));
                        }
                        if (asset.getPictureUri() != null && !asset.getPictureUri().equals("")) {
                            String imgPath = ImageUtils.imageToBase64(asset.getPictureUri());
                            asset.setImagpath(imgPath);
                        }
                    }
                    check.setAssetList(assetList);
                }
                uploadCheck(check);
            }
        }
    }

    // 上传验收单
    public void uploadCheck(final Check check) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = gson.toJson(check);
                try {
                    checkService.uploadCheckList(json, new Callback() {
                        @Override
                        public void onFailure(Call call, final IOException e) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (listener != null) {
                                        listener.onFail(check.getId_(), OrderType.CHECK, e, --sum);
                                    }
                                }
                            });

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String json = response.body().string();
                            if (json != null) {
                                final Result<String> result = gson.fromJson(json, new TypeToken<Result<String>>() {
                                }.getType());
                                if (result != null && result.getHttpCode() == 200) {
                                    // 删除本地单子
                                    session.getCheckDao().deleteByKey(check.getCheck_id());
                                    session.getAssetDao().deleteInTx(check.getAssetList());
                                    for (Asset asset : check.getAssetList()) {
                                        if (asset.getPictureUri() != null) {
                                            ImageUtils.deleteImage(asset.getPictureUri());
                                        }
                                    }
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onSucces(check.getId_(), OrderType.CHECK, --sum);
                                            }
                                        }
                                    });

                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (listener != null) {
                                                listener.onFail(check.getId_(), OrderType.CHECK, new BusinessErrorException(result.getMsg()), --sum);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                } catch (final Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (listener != null) {
                                listener.onFail(check.getId_(), OrderType.CHECK, e, --sum);
                            }
                        }
                    });
                }
            }
        }).start();
    }

}
